<template>
  <div class="container">
    <div class="app-container">
      <el-tree :data="depts" :props="{ label: 'name' }" default-expand-all>
        <template #default="{ data }">
          <el-row style="width: 100%">
            <el-col :span="20">{{ data.name }}</el-col>
            <el-col :span="4">
              <el-row>
                <el-col :span="12">{{ data.managerName || "暂无" }}</el-col>
                <el-col :span="12">
                  <el-dropdown @command="handleCommand($event, data.id)">
                    <span class="el-dropdown-link">
                      操作<i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        command="add"
                      >添加部门</el-dropdown-item>
                      <el-dropdown-item
                        command="edit"
                      >编辑部门</el-dropdown-item>
                      <el-dropdown-item
                        command="del"
                      >删除部门</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <add-dept ref="addDept" :show-dialog.sync="showDialog" :source-depts="sourceDepts" :pid="pid" @reload="getDepts" />
  </div>
</template>
<script>
import { reqGetDepts, reqDelDept } from '@/api/department'
import AddDept from './add-dept.vue'
import { translateToTreeData } from '@/utils/index'
export default {
  name: 'Department',
  components: {
    AddDept
  },
  data() {
    return {
      depts: [], // 部门列表
      sourceDepts: [], // 存一份原始数据
      showDialog: false, // 控制弹出框得显示与隐藏
      pid: 0
    }
  },
  created() {
    this.getDepts()
  },
  methods: {
    async getDepts() {
      const { data } = await reqGetDepts()
      console.log(data)
      this.sourceDepts = data
      this.depts = translateToTreeData(data, 0)
    },

    async handleCommand(command, id) {
      if (command === 'add') {
        this.showDialog = true
        this.pid = id
        // console.log('添加')
        this.$refs.addDept.title = '新增部门'
      }
      if (command === 'edit') {
        // console.log('修改')
        this.showDialog = true
        this.pid = id
        this.$nextTick(() => {
          this.$refs.addDept.showEditDept()
        })
        this.$refs.addDept.title = '修改部门'
      }
      if (command === 'del') {
        // console.log('删除')
        const str = await this.$confirm('你确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {})
        if (str === 'confirm') {
          await reqDelDept(id)
          this.getDepts()
        }
        console.log('confirm')
      }
    }
  }
}
</script>
